package com.thoughtworks.bytecode2class.attribute;

import com.thoughtworks.bytecode2class.ClassReader;
import com.thoughtworks.bytecode2class.constantpool.Utf8Constant;

public abstract class Attribute {

    protected int length;
    protected ClassReader classReader;
    private String name;

    public Attribute(ClassReader classReader, String name) {
        this.classReader = classReader;
        this.name = name;
        parseLength();
        parseAttributeContent();
    }

    private void parseLength() {
        this.length = classReader.forwardWord();
    }

    protected abstract void parseAttributeContent();
    
    public String getName() {
        return name;
    }

    public static Attribute create(ClassReader classReader) {
        int attributeNameIndex = classReader.forwardChar();
        Utf8Constant constant = classReader.getConstantPool().getUtf8Constant(attributeNameIndex);
        String name = constant.getValue();
        if (name.equals("Code")) {
            return new CodeAttribute(classReader, name);
        }
        if (name.equals("Exceptions")) {
            return new ExceptionsAttribute(classReader, name);
        }
        if (name.equals("InnerClasses")) {
            return new InnerClassesAttribute(classReader, name);
        }
        if (name.equals("SourceFile")) {
            return new SourceFileAttribute(classReader, name);
        }
        return new UnknownAttribute(classReader, name);
    }

}
